import * as storage from '@/common/utils/storage';

class User {
    constructor(user) {
        // 避免user为null
        if (!user) user = {}
        this.id = user.id || -1
        this.username = user.username || ''
        // this.avatar = user.avatar || ''
    }
}
const token = storage.getSessionToken() || storage.getLocalToken() || ''
const user = new User(storage.getSessionUser())

export default {
    state: () => ({
        token, user
    }),
    getters: {
        /**
         * 判断是否登录
         * @param {*} state 
         */
        isLogin: (state) => state.user.id !== -1
    },
    mutations: {
        /**
         * 设置用户的值
         * @param {*} state 
         * @param {*} user 
         */
        SET_USER(state, user) {
            state.user = new User(user)
        },
        /**
         * 设置token的值
         * @param {*} state 
         * @param {*} token 
         */
        SET_TOKEN(state, token) {
            state.token = token
        }
    },
    actions: {
        loginSuccess(context, data) {
            const { token, isRememberme, ...user } = data
            context.commit("SET_USER", user)
            context.commit("SET_TOKEN", token)
            // 将用户信息存入sessionStorage
            storage.setSessionToken(token)
            storage.setSessionUser(user)

            /**
             * 如果用户选择记住密码，则将token存储到localStorage中，
             * 下次登录，用token获取用户信息，并跳转到首页
             */
            if (isRememberme) {
                storage.setLocalToken(token)
            } else {
                storage.removeLocalToken()
            }
        },
        logoutSuccess(context) {
            context.commit('SET_TOKEN', '')
            context.commit('SET_USER', {})
            context.commit('RESET_TABS_VALUE')
            storage.removeLocalToken()
            storage.removeSessionToken()
            storage.removeSessionUser()
            storage.removeSessionTabsValue()
        }
    }
}